package com.maxd.service.selfAliPay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.maxd.constants.AliPayConstants;
import com.maxd.model.Orders;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.selfOrder.OrdersJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SelfAliPayServiceImpl implements SelfAliPayService{
    @Autowired
    private OrdersJpaRepository ordersJpaRepository;
    @Autowired
    private CommonRepository commonRepository;

    @Override
    public boolean refund(Long ordersId) {
        try {
            Orders orders = ordersJpaRepository.findById(ordersId).orElse(null);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(orders.getPayNum()); //订单号
            model.setRefundAmount(orders.getPayMoney()+""); //退款金额
            model.setOutRequestNo(orders.getOrderNum()); //退款单号
            request.setBizModel(model);
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return true;
            } else {
                return false;
            }
        }catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return false;
    }
}
